package com.lin.service.MulThread;

import cn.hutool.core.util.RandomUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierCase {
    //匹配游戏->选择角色->加载进入
    public static void produce(){
        List<String> player = new ArrayList<>();
        player.add("玩家一");
        player.add("玩家二");
        player.add("玩家三");
        player.add("玩家四");
        CyclicBarrier barrier = new CyclicBarrier(player.size());
        for (int i = 0; i < player.size(); i++) {
            new Thread(() -> {
                String threadName = Thread.currentThread().getName();
                sleep(); //准备游戏时间
                System.out.println(threadName+"准备完成");
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
                sleep(); //选择角色时间
                System.out.println(threadName + "选择完成");
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
                sleep(); //加载进入时间
                System.out.println(threadName + "加载完成");
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            },player.get(i)+"线程").start();
        }
    }
    public static void sleep(){
        //睡1到3秒的随机数
        int random = RandomUtil.randomInt(1000, 3000);
        try {
            Thread.sleep(random);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        produce();
    }
}
